package com.tjc.cloud.util.signature

import java.security.KeyFactory
import java.security.Signature
import java.security.spec.PKCS8EncodedKeySpec
import java.util.*

val ALGORITHM_SHA1_WITH_RSA = "SHA1withRSA"
val ALGORITHM_RSA = "RSA"
val CHARSET_UTF_8 = "UTF-8"
fun Map<String, String>.signWithRSA(privateKey: String) =
        this.keys.sorted().map { "$it=${this[it]}" }.reduce { acc, s -> "$acc&$s" }
                .signWithRSA(privateKey)

fun String.signWithRSA(privateKey: String): String? {
    val spec = PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey))
    val keyFactory = KeyFactory.getInstance(ALGORITHM_RSA)
    val pk = keyFactory.generatePrivate(spec)
    val signature = Signature.getInstance(ALGORITHM_SHA1_WITH_RSA)
    signature.initSign(pk)
    signature.update(this.toByteArray(charset(CHARSET_UTF_8)))
    return Base64.getEncoder().encodeToString(signature.sign())
}
